package com.mysite.seckill.web.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.mysite.seckill.commons.common.Constant;
import com.mysite.seckill.commons.exception.BusinessError;
import com.mysite.seckill.commons.po.User;
import com.mysite.seckill.commons.vo.ResultVo;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String X_REQUESTED_WITH = "X-Requested-With";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.err.println(request.getRequestURI());

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user == null) {
            try {
                if (request.getHeader(X_REQUESTED_WITH) != null || request.getParameter(X_REQUESTED_WITH) != null) {
                    PrintWriter printWriter = response.getWriter();
                    printWriter.write(JSON.toJSONString(new ResultVo(BusinessError.USER_SESSION_TIMEOUT_ERROR)));
                    printWriter.flush();
                    printWriter.close();
                } else {
                    response.sendRedirect("/");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}
